from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.shortcuts import render
from .models import EnvironmentData, CardData
from django.contrib.auth.models import User
import json
from django.http import JsonResponse
from djangoProject.mqtt import mqtt_client  # 修改导入语句
from django.contrib.auth import logout  # 添加导入

def login_view(request):
    if request.method == 'POST':
        # 添加登录验证逻辑
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('back:dashboard')
    return render(request, 'back/login.html')




def register_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')
        
        if password1 != password2:
            return render(request, 'back/register.html', {'error': '密码不匹配'})
        
        # 检查用户名是否已存在
        if User.objects.filter(username=username).exists():
            return render(request, 'back/register.html', {'error': '用户名已存在'})
        
        # 创建用户
        user = User.objects.create_user(username=username, password=password1)
        
        # 自动登录用户
        user = authenticate(username=username, password=password1)
        login(request, user)
        
        # 注册成功后重定向到仪表盘页面，这里假设仪表盘的 URL 名称为 'dashboard'
        return redirect('login')
    
    return render(request, 'back/register.html')

#


def dashboard_view(request):
    if not request.user.is_authenticated:
        return redirect('login')
    environment_data = EnvironmentData.objects.all()
    card_data = CardData.objects.all()
    return render(request, 'back/dashboard.html', {
        'environment_data': environment_data,
        'card_data': card_data,
    })


# def write_card(request):
#     if request.method == 'POST':
#         card_number = request.POST.get('card_number')
#         information = request.POST.get('information')

#         # 准备数据为 JSON
#         data = {
#             'card_number': card_number,
#             'information': information
#         }
#         payload = json.dumps(data)

#         # 发布到 MQTT 主题
#         try:
#             # 发布到 MQTT 主题
#             publish_message(request, topic='/writecard', msg=payload)

#             # 保存到数据库
#             CardData.objects.create(card_number=card_number, information=information)
#             return HttpResponse('数据成功发送至 MQTT 主题 /writecard!')
        
#         except Exception as e:
#             return HttpResponse(f'无法发布数据到 MQTT: {str(e)}')

#         return redirect('dashboard')

#     return render(request, 'back/write_card.html')
# 修正 publish_message 函数定义
def publish_message(request):
    try:
        request_data = json.loads(request.body)
        topic = request_data.get('topic')
        msg = request_data.get('msg')
        rc, mid = mqtt_client.client.publish(topic, msg)  # 通过实例访问client属性
        return JsonResponse({'code': rc})
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)

def publish_message1(request, topic, msg):
    try:
        rc, mid = mqtt_client.publish(topic, msg)
        return JsonResponse({'code': rc})
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)
    
# 更新 write_card 视图函数
def write_card(request):
    if request.method == 'POST':
        card_number = request.POST.get('card_number')
        information = request.POST.get('information')
        data = {'card_number': card_number, 'information': information}
        payload = json.dumps(data)

        try:
            # 发布到 MQTT 主题
            publish_message1(request, topic='/writecard', msg=payload)

            # 保存到数据库
            CardData.objects.create(card_number=card_number, information=information)
            return HttpResponse('数据成功发送至 MQTT 主题 /writecard!')

        except Exception as e:
            return HttpResponse(f'无法发布数据到 MQTT: {str(e)}')

        return redirect('dashboard')

    return render(request, 'back/write_card.html')

def read_card(request):
    if not request.user.is_authenticated:
        return redirect('login')

    latest_environment_data = EnvironmentData.objects.all()
    print(latest_environment_data)
    # print(animals)

    return render(request, 'back/dashboard.html', {
        'environment_data': latest_environment_data,
    })

def send_mqtt_message(request):
    if request.method == 'POST':
        try:
            request_data = json.loads(request.body)
            topic = request_data.get('topic')
            message = request_data.get('message')
            if not topic or not message:
                return JsonResponse({'status': 'invalid parameters'}, status=400)
                
            # 修复此处调用方式，通过client属性访问
            rc, mid = mqtt_client.client.publish(topic, message)
            return JsonResponse({'status': 'success', 'rc': rc})
        except json.JSONDecodeError as e:
            return JsonResponse({'status': 'error', 'message': f'Invalid JSON: {str(e)}'}, status=400)
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=500)

def door_control(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            payload = json.dumps({
                'action': data.get('action'),
                'value': data.get('value')
            })
            rc, mid = mqtt_client.client.publish('/door', payload)
            return JsonResponse({'status': 'success', 'rc': rc})
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=400)
    return JsonResponse({'status': 'method not allowed'}, status=405)


def logout_view(request):
    logout(request)
    return redirect('login')


def write_finger(request):
    if not request.user.is_authenticated:
        return redirect('login')
    
    if request.method == 'POST':
        user_id = request.POST.get('user_id')
        # 这里添加指纹数据处理逻辑
        try:
            # 示例MQTT发布
            payload = json.dumps({'user_id': user_id})
            rc, mid = mqtt_client.client.publish('/fingerprint', payload)
            return HttpResponse('指纹数据已发送')
        except Exception as e:
            return HttpResponse(f'操作失败: {str(e)}')
    
    return render(request, 'back/write_finger.html')

def write_password(request):
    # 密码录入逻辑
    return render(request, 'back/write_password.html')